<template>
  <div>
    <!-- 用户视口,超出部分滚动 -->
    <div class="viewPort" ref="viewPort" :style="{'--rowHeight': `${rowHeight}px`}" @scroll="onScroll"> 
      <!-- 子元素超出父元素高度,才能滚动 -->
      <div class="scrollbar" ref="scrollbar"></div>
      <!-- 数据列表 -->
      <div class="list" ref="list">
        <div class="row" v-for="(item, index) in showList" :key="index">
          {{ item.n }}
        </div>
      </div>
    </div>
    <List></List>
  </div>
</template>

<script>
import List from "./list.vue";
export default {
  data () {
    const bigList = new Array(20000).fill(null).map((item, i)=>({ n: i+ 1}))
    console.log("🚀 ~ file: index.vue:11 ~ bigList:", bigList)
    return {
      list: Object.freeze(bigList),
      viewCount: 20, // 显示多少条数据
      rowHeight: 20, // 每条数据行高
      start: 0,
      end: 20,
      list1: {
        name:'123'
      }
    }
  },
  components: {
    List
  },
  computed:{
    showList(){
      return this.list.slice(this.start, this.end)
    },
  },
  mounted() {
    this.$refs.viewPort.style.height = `${this.rowHeight * this.viewCount}px`
    this.$refs.scrollbar.style.height = `${this.rowHeight * this.list.length}px`

    console.log(this.list1);
  },
  methods: {
    onScroll() {
      let offsetTop = this.$refs.viewPort.scrollTop;
      this.start = Math.round(offsetTop / this.rowHeight);
      this.end = this.start + this.viewCount;

      this.$refs.list.style.transform = `translateY(${offsetTop}px)`

      console.log(offsetTop,this.$refs.viewPort.scrollTop);
    },
  },
}

</script>
<style scoped lang='less'>
.viewPort {
  // height: 400px;
  width: 300px;
  background-color: yellowgreen;
  position: fixed;
  left: 0;
  top: 0;
  bottom: 0;
  right: 0;
  margin: auto;
  overflow-y: scroll;
  .scrollbar {
    // height: 3000px;
  }
  .list {
    position: absolute;
    left: 0;
    top: 0;
    .row {
      // height: 20px;
      height: var(--rowHeight);
    }
  }
}
</style>